#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <map>
#include <list>
#include "uthreads.hh"

const char *LIRR = "thread library error: ";

void f()
{
  printf("tid = %d\n", thread_gettid());

  if (thread_gettid() == 1) {
    int ret = thread_sleep(thread_gettid(), 1000);
    if (ret == 0)
      printf("tid = %d after sleep\n", thread_gettid());
  }
  for(int j = 0; j < 100000000; j++) {
  }
  printf("%d synching\n", thread_gettid());

  thread_sync(thread_gettid()%2,3);
  printf("%d after synch\n", thread_gettid());
  printf("%d synching b\n", thread_gettid());
  thread_sync(thread_gettid()%2,3);
  printf("%d after synch\n", thread_gettid());
  thread_terminate(thread_gettid());
}


int main(int argc, char* argv[])
{
  thread_lib_init();
  thread_spawn(f);
  thread_spawn(f);
  printf("time to wake: %d\n", thread_get_time_until_wakeup(1));
  printf("terminated 1\n");
  printf("num sync1: %d, num sync2: %d\n", thread_get_num_waiting_for_sync(0),
         thread_get_num_waiting_for_sync(1));
  thread_spawn(f);
  thread_spawn(f);
  printf("num sync1: %d, num sync2: %d\n", thread_get_num_waiting_for_sync(0),
         thread_get_num_waiting_for_sync(1));
  printf("time to wake: %d\n", thread_get_time_until_wakeup(1));
  thread_terminate(1);
  thread_spawn(f);
  thread_spawn(f);
  thread_spawn(f);
  printf("all done\n");
  return 0;
}

